package servlet;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class XuLyDangKy
 */
public class XuLyDangKy extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public XuLyDangKy() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}

	private void doAction(HttpServletRequest request,
			HttpServletResponse response) {

		String email = request.getParameter("email");
		String email_err = "";
		String password = request.getParameter("password");
		String repassword = request.getParameter("re_password");
		String tinh = request.getParameter("tinh");

		if (email == null || email.trim().equals("")) {
			email_err = "Ban chua nhap dia chi email";
		} else {
			Pattern p_email = Pattern
					.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
			Matcher matcher_email = p_email.matcher(email);
			if (!matcher_email.matches()) {
				email_err += "Dia chi email khong hop le";
			}
		}

		request.setAttribute("email", email);
		request.setAttribute("tinh", tinh);
		request.setAttribute("email_err", email_err);
		if (email_err.length() > 0) {
			RequestDispatcher rd = getServletContext().getRequestDispatcher(
					"/register.jsp");
			try {
				rd.forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
